package com.lihui.TCP;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * 功能描述
 *
 * @author wileda
 * @date 2023/02/28  14:06
 */
public class TCPEchoClient {
    //声明Socket 对象
    private Socket socket;


    public TCPEchoClient(String serverIp, int port) throws IOException {
        //根据端口号和ip地址创建Socket对象
        this.socket = new Socket(serverIp,port);
    }
    /**
     * 启动服务
     */
    public void start(){
        System.out.println("客户端已启动.");
        //从socket中获取输入与输出对象
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            //循环接收用户输入
            while(true){
                System.out.println("->");
                Scanner scanner = new Scanner(System.in);
                String request = scanner.nextLine();
                //非空校验
                if(request == null || request.equals("")){
                    System.out.println("输入的内容不能为空.");
                    continue;
                }

                //2.把用户的输入封装到输入流中
                PrintWriter writer = new PrintWriter(outputStream);
                //3.把数据发送出去
                writer.println(request);
                //刷新缓存区
                writer.flush();
                //4.接收服务器响应，可以通过Scanner简化
                Scanner responseScanner = new Scanner(inputStream);
                //5.解析响应的数据
                String response = responseScanner.nextLine();
                //6.打印日志
                System.out.printf("request = %s,response = %s",request,response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoClient client = new TCPEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
